<template>
  <div :id="id" :style="{ height:height,width:width }" />
</template>

<script>
import echarts from "echarts";
export default {
  props: {
    id: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "2270px",
    },
    data: {
      type: Array,
      default: () => [],
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      chart: null,
      legendData: [],
      echartData: [],
      plusImg:
        "path://M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm192 472c0 4.4-3.6 8-8 8H544v152c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V544H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h152V328c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v152h152c4.4 0 8 3.6 8 8v48z",
      minusImg:
        "path://M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm192 472c0 4.4-3.6 8-8 8H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h368c4.4 0 8 3.6 8 8v48z",
      emptyImg: "circle",
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id));
      // 这里我选的图片是透明背景的，如果使用白色背景的图片就可以遮盖节点后的线条了
      let plusImg =
       "";

      let minusImg =
        "";

      let emptyImg =
        "";

      // 获取节点显示的图片
      const getSymbolImg = (item = {}) => {
        return `image://${
          item.children && item.children.length
            ? minusImg
            : item.children_bak && item.children_bak.length
            ? plusImg
            : emptyImg
        }`;
      };

      // 基础配置option
      const commonOption = {
        animation: false,
        series: [
          {
            type: "tree",
            left: "18%",
            right: "20%",
            top: "1%",
            bottom: "2%",
            orient: "LR", //方向
            // initialTreeDepth: 1, //深度
            symbol: "circle",
            symbolSize: 20,
            itemStyle: {
              color: "#ffad3d",
              borderColor: "rgba(255,255,255,.1)",
            },

            lineStyle: {
              width: 1,
              curveness: 0.5,
            },
            label: {
              normal: {
                position: "left",
                verticalAlign: "middle",
                distance: 100,
                align: "center",
                color: "#fff",
                borderRadius: 15,
                lineHeight:15,
                width:200,
                backgroundColor: '#eee',
                borderColor: '#777',
                borderWidth: 1,
                borderRadius: 4,
                padding:[10,0,10,0],
                formatter: function (params) {
                  var question = params.name.replace(/[^\x00-\xff]/g, "$&\x01").replace(/.{30}\x01?/g, "$&\n").replace(/\x01/g, "")+"\n"
                  var questionTitle = "{title|"+question+"}"+"{hr|}\n"
                  if(params.data.nodeList){
                    for(var i = 0;i<params.data.nodeList.length;i++){
                      var index = i+1
                      var list = "{list|"+index+'、'+params.data.nodeList[i].replace(/[^\x00-\xff]/g, "$&\x01").replace(/.{26}\x01?/g, "$&\n").replace(/\x01/g, "")+"}"+"\n"
                      questionTitle+=list
                    }
                  }
                  return questionTitle
                },
                rich: {
                  title: {
                    color:'#333',
                    align: 'left',
                    padding:[10,10,10,10]
                  },
                  hr: {
                    borderColor: '#777',
                    width: 200,
                    borderWidth: 0.5,
                    height: 0
                  },
                  box: {
                    height: 30,
                    color: "#fff",
                    align: "center",
                    borderRadius: 30,
                  },
                  list:{
                    align: 'left',
                    color:'#333',
                    padding:[10,10,10,10]
                  }
                },
              },
            },
            leaves: {
              label: {
                normal: {
                  position: "right",
                  verticalAlign: "middle",
                  distance: 0,
                  align: "left",
                  color: "#333",
                  lineHeight:20,
                  formatter: function (params) {
                    var question = params.name.replace(/[^\x00-\xff]/g, "$&\x01").replace(/.{30}\x01?/g, "$&\n").replace(/\x01/g, "")+"\n"
                    var questionTitle = "{title|"+question+"}"+"{hr|}\n"
                    if(params.data.nodeList){
                      for(var i = 0;i<params.data.nodeList.length;i++){
                        var index = i+1
                        var list = "{list|"+index+'、'+params.data.nodeList[i].replace(/[^\x00-\xff]/g, "$&\x01").replace(/.{26}\x01?/g, "$&\n").replace(/\x01/g, "")+"}"+"\n"
                        questionTitle+=list
                      }
                    }
                    return questionTitle
                  },
                  rich: {
                     title: {
                      color:'#333',
                      align: 'left',
                      padding:[10,10,10,10]
                    },
                    hr: {
                      borderColor: '#777',
                      width: 200,
                      borderWidth: 0.5,
                      height: 0
                    },
                    box: {
                      height: 30,
                      color: "#fff",
                      align: "center",
                      borderRadius: 30,
                    },
                    list:{
                      align: 'left',
                      color:'#333',
                      padding:[10,10,10,10]
                    }
                  },
                },
              },
              symbolOffset: [8, 0],
            },
          },
        ],
      };
      // const respData = this.data
      // console.log(respData)
      // 原始数据
      const respData = [
        {
          level: 0,
          name: "发生机车热轴时处理程序",
          id: "发生机车热轴时处理程序",
        },
        {
          level: 1,
          name: "轴承温度异常升高",
          id: "轴承温度异常升高",
          category: "official_media",
          parent_node_id: "发生机车热轴时处理程序",
          nodeList:[
            "发现轴温异常报警，立即对报警点轴位、温度进行检查，判断是否为误报警",
            "确认轴承超温后，立即采取减速措施",
            "确认轴承超温并采取减速措施后，切除故障轴温动力"
          ]
        },
        {
          level: 2,
          name: "轴承温度不再升高且后部瞭望无异常",
          id: "5ee2e966e772c4edae391b2d",
          parent_node_id: "轴承温度异常升高",
          nodeList:[
            "轴承温度不再升高且后部瞭望无异常后，将主手柄置于牵引区，继续维持运行",
            "维持运行后，联系车站值班员请求在站内停车检查",
            "列车运行至站内，停车",
            "在站内停车检查发现轴承温度无异常，汇报车站值班员"
          ]
        },
        {
          level: 2,
          name: "轴承温度迅速上升或后部瞭望发现异状",
          id: "5ee2e966e772c4edae391b2d",
          parent_node_id: "轴承温度异常升高",
          nodeList:[
            "轴承温度继续升高，停车",
            "停车后，将情况汇报车站值班员",
            "列车运行至站内，停车",
            "检查完成后，联系车站值班员，请求救援和摘机车溜轴降温",
            "机车摘好后，起动机车前移",
            "前移完成后，停车",
            "前移完成并停车后，启动机车进行溜轴降温"
          ]
        },
        {
          level: 1,
          name: "轴承、齿轮或踏面振动报警",
          id: "轴承、齿轮或踏面振动报警",
          category: "official_media",
          parent_node_id: "发生机车热轴时处理程序",
          nodeList:[]
        },
        {
          level: 2,
          name: "二级振动报警",
          id: "二级振动报警",
          parent_node_id: "轴承、齿轮或踏面振动报警",
          nodeList:[
            "对报警点轴位，温度进行检查"
          ]
        },
        {
          level: 3,
          name: "伴随轴承温度异常升高",
          id: "伴随轴承温度异常升高",
          parent_node_id: "二级振动报警",
          nodeList:[
            "确认轴承超温后，立即采取减速措施",
            "确认轴承超温并采取减速措施后，切除故障轴温动力"
          ]
        },
        {
          level: 4,
          name: "轴承温度不再升高且后部瞭望无异常",
          id: "轴承温度不再升高且后部瞭望无异常",
          parent_node_id: "伴随轴承温度异常升高",
          nodeList:[
            "轴承温度不再升高且后部瞭望无异常后，将主手柄置于牵引区，继续维持运行",
            "维持运行后，联系车站值班员请求在站内停车检查",
            "列车运行至站内，停车",
            "在站内停车检查发现轴承温度无异常，汇报车站值班员"
          ]
        },
        {
          level: 4,
          name: "轴承温度迅速上升或后部瞭望发现异状",
          id: "轴承温度迅速上升或后部瞭望发现异状",
          parent_node_id: "伴随轴承温度异常升高",
          nodeList:[
            "轴承温度继续升高，停车",
            "停车后，将情况汇报车站值班员",
            "检查完成后，联系车站值班员，请求救援和摘机车溜轴降温",
            "机车摘好后，起动机车前移",
            "前移完成后，停车",
            "前移完成并停车后，启动机车进行溜轴降温"
          ]
        },
        {
          level: 3,
          name: "不伴随轴承温度异常升高",
          id: "不伴随轴承温度异常升高",
          parent_node_id: "二级振动报警",
          nodeList:[
            "维持运行到前方停车站检查"
          ]
        },
        {
          level: 2,
          name: "一级振动报警",
          id: "一级振动报警",
          parent_node_id: "轴承、齿轮或踏面振动报警",
          nodeList:[
            "对报警点轴位，温度进行检查",
            "无其他异常情况时，维持运行到前方停车站检查"
          ]
        },
      ];
      respData.forEach((item, index) => {
        item.id = index;
        if(item.level === 0){
          item.backgroundColor='#0099CC'
        }
        if(item.level === 1){
          if(item.category ==='official_media'){
            item.backgroundColor='#66CC00'
          }
          if(item.category ==='mainstream_media'){
            item.backgroundColor='#FFC000'
          }
          if(item.category ==='we_media'){
            item.backgroundColor='#CC6600'
          }
        }
      });
      respData.forEach((item, index) => {
        if (item.parent_node_id) {
          for (let index = 0; index < respData.length; index++) {
            if (item.parent_node_id === respData[index].name) {
              item.parent_node_id = respData[index].id;
            }
          }
        }
      });
      console.log(respData);
      const originalData = [];
      respData.forEach((item, index) => {
        originalData[item.id] = item;
      });
      console.log(originalData);
      // 数据处理
      const innerData = [];
      Object.values(originalData).forEach((item, index) => {
        if (innerData[item.level] && innerData[item.level].length) {
          innerData[item.level].push(item);
        } else {
          innerData[item.level] = [item];
        }
      });
      console.log(innerData);
      for (let i = innerData.length - 1; i >= 0; i--) {
        // 每个item和result中的每个对象是同一引用
        console.log(innerData[i]);
        innerData[i].forEach((item, index, all) => {
          item.close = function (state) {
            if (this.children) {
              if (this.children_bak.length) {
                if (state === true || this.children.length) {
                  this.children = [];
                  this.children_bak.forEach((child) => {
                    child.close(true);
                  });
                } else {
                  this.children = this.children_bak;
                }
                this.symbol = getSymbolImg(this);
              }
            }
          };
          if (i !== innerData.length - 1) {
            item.children = [];
            item.children_bak = [];
            item.add = function (it) {
              if (!!it) {
                this.children.push(it);
                this.children_bak.push(it);
              }
            };
            innerData[i + 1].forEach((child) => {
              if (+child.parent_node_id === +item.id) {
                item.add(child);
              }
            });
          }
          if (i === 0) {
            item.label = {
              normal: {
                rotate: 0,
                align: "center",
                color: "#333",
                distance: 100,
                width:150,
                backgroundColor: "#fff",
                formatter: function (params) {
                  var question = params.name.replace(/[^\x00-\xff]/g, "$&\x01").replace(/.{30}\x01?/g, "$&\n").replace(/\x01/g, "")
                  return question
                },
              },
            };
          } else {
            if (item.level !== 2) {
              item.label = {
                position: "left",
                verticalAlign: "middle",
                distance: 200,
                align: "left",
                color: "#333",
                backgroundColor: "#fff",
              };
            } else {
              item.label = {
                backgroundColor: "#fff",
              };
            }
          }
          item.symbol = getSymbolImg(item);
        });
      }

      // 单个节点的点击事件
      const clickFun = (param) => {
        //因为保存了对象同一引用，所以可以使用originalData快速找到目标对象
        let aimObj = originalData[param.data.id];
        if(originalData[param.data.id].url){
          window.open(originalData[param.data.id].url, "_blank");
        }
        // 组合模式实现关闭开启
        aimObj.close();
        // 手动关闭tooltip不然会出现不可关闭的tooltip
        this.chart.dispatchAction({
          type: "hideTip",
        });
        this.chart.clear();
        commonOption.series[0].data = innerData[0];
        if (originalData[param.data.id].children) {
          if (originalData[param.data.id].children.length === 0) {
            if (originalData[param.data.id].level === 0) {
              commonOption.series[0].leaves.label.normal.position = "left";
              commonOption.series[0].leaves.label.normal.distance = 100;
            }
          } else {
            commonOption.series[0].leaves.label.normal.position = "right";
            commonOption.series[0].leaves.label.normal.distance = 0;

          }
          console.log(commonOption);
        }
        this.chart.setOption(commonOption, true);
      };

      commonOption.series[0].data = innerData[0];
      this.chart.setOption(commonOption, true);

      this.chart.on("click", clickFun);
    },
  },
};
</script>